import Vue from 'vue'
import Router from 'vue-router'
import Auth from '@/utils/Auth'

Vue.use(Router)

const router = new Router({
  routes: [
    { path: '/', name: 'Index', component: resolve => { require(['@/public/Index.vue'], resolve) } },
    { path: '/test', name: 'Test', component: resolve => { require(['@/public/Test.vue'], resolve) } },
    { path: '/login', name: 'Login', component: resolve => { require(['@/public/Login.vue'], resolve) } },
    { path: '/register', name: 'Register', component: resolve => { require(['@/public/Register.vue'], resolve) } }
  ]
})

const whiteList = ['/', '/login', '/test']

router.beforeEach((to, from, next) => {
  if (!Auth.isLogin()) {
    if (whiteList.indexOf(to.path) > -1 || whiteList.indexOf(to.path + '/*') > -1) {
      next()
    } else {
      next({ name: 'Login' })
    }
  } else {
    if (to.name === 'Login') {
      next({ name: 'Index' })
    } else {
      next()
    }
  }
})

export default router
